package net.pingfang.devicelock.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.task.TaskExecutor;
import org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNetServerConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNioClientConnectionFactory;
import org.springframework.integration.ip.tcp.serializer.AbstractByteArraySerializer;
import org.springframework.integration.ip.tcp.serializer.ByteArrayRawSerializer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
public class ParamCommon {

    public static byte[] deserialize(InputStream inputStream, byte SIGN){
        try{
            log.info("收到回传值:{}",inputStream.read());
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int currentByte;
            boolean inFrame = true;
            // 16进制接收
            while ((currentByte = inputStream.read()) != -1) {
                buffer.write(currentByte);
                if (currentByte == SIGN ) {
                    if (inFrame) {
                        inFrame = false;
                    } else {
                        return buffer.toByteArray(); // 返回完整报文（含7E）
                    }
                }
            }
        }catch (IOException e){
            log.error("在接收TCP报文时发生分隔符异常，{}",e.getMessage());
        }
        return null;
    }

    public static TcpNetServerConnectionFactory toTcpServerFactory(int port, AbstractByteArraySerializer ar,
                                          TaskExecutor taskExecutor){
        TcpNetServerConnectionFactory factory = new TcpNetServerConnectionFactory(port);
        //电子锁报文应该是以7E XX XX XX ... XX 7E结尾的一段 7E == 0X7E?
//        factory.setSerializer(new TestSerializer()); // 使用byte 59 69作为分隔报文
//        factory.setDeserializer(new TestSerializer());
        factory.setSerializer(ar); // 使用16进制7E分隔报文
        factory.setDeserializer(ar);
        factory.setSoTimeout(5_000);  // 设置Socket读取超时（单位：毫秒）
        factory.setTaskExecutor(taskExecutor);
        factory.setSingleUse(false);
        factory.setSoKeepAlive(true);
        return factory;
    }


    public static AbstractClientConnectionFactory clientConnectionFactory(int port, String host,
                                                                          TaskExecutor taskExecutor) {
        TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory(host,port);
        factory.setSingleUse(false);      // 启用连接复用
        factory.setSerializer(new ByteArrayRawSerializer());  // 使用原始字节流序列化器
        factory.setDeserializer(new ByteArrayRawSerializer());
        factory.setReadDelay(30_000);
        factory.setTaskExecutor(taskExecutor);
        return factory;
    }
}
